import React, { Component } from 'react';
import { Input, Col, Select, Button, Tooltip, Tag, Pagination, Checkbox, Radio, Icon, Row, Badge, message } from 'antd';

import Link from 'umi/link';
import axios from 'axios';
import Api from '../../services/apis';
import IframeComm from "../../components/IframeComm";
import QueueAnim from 'rc-queue-anim';

import Info from "./Info";
import Chart from "./Chart";

import styles from "./style.less";

const InputGroup = Input.Group;
const Option = Select.Option;
const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;

const noPic = '';


class AssetMap extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showList: false,
      page: 1,
      resultDatas: [],
      resultDatasCount: 0,
      showFilter: false,
      qsxz: ['保障性住房', '公房', '学校宿舍', '住宅', '临建房', '车库'],
      zczt: ['接管中', '待接管', '已接管', '运营中'],
      zlzt: ['待租赁', '租赁中'],
      zlValue: ['待租赁', '租赁中'],
      qsValue: ['保障性住房', '公房', '学校宿舍', '住宅', '临建房', '车库'],
      zcValue: ['接管中', '待接管', '已接管', '运营中'],
      right: -380,
      nowType: 'info',
      sendMapData: {
        type: "all",
        data: []
      },
      searchType: 1,
      timer: '',
      res: [],
      searchVal: '',
      showLoading: false,
      communityVal: [],
      arrVal: {
        props: {
          children: ''
        }
      },
      cityData: {},
      postData: {},
      infoData: {
        buildingArea: 0,
        buildingCount: 0,
        houseCount: 0,
        landArea: 0,
        projectCount: 0,
        rentingArea: 0,
        waitRentArea: 0,
        xArr: [],
        xArrFee: [],
        yArr: [],
        yArrFee: []
      },
      clickXQ: {
        "communityName": "",
        "communityId": "",
        "address": "",
        "buildCount": '',
        "houseCount": '',
        "xCoord": "",
        "yCoord": "",
        "cityCode": "",
        "city": ""
      },
      showMapDiv: false
    };
  }
  searchVal(val) {
    let resultDatas = [];
    switch (Number(this.state.searchType)) {
      case 1:
        for (let i = 0, outLen = val.length; i < outLen; i++) {
          resultDatas.push({
            badge: (i + 1).toString(),
            projectName: val[i].projectName,
            projectCode: val[i].projectCode,
            totalBuildingArea: val[i].totalBuildingArea,
            totalLandArea: val[i].totalLandArea,
            buildCount: val[i].buildCount,
            houseCount: val[i].houseCount,
            receivedDate: val[i].receivedDate,
            transferUnit: val[i].transferUnit,
            isTitle: true
          });
          for (let j = 0, inLen = val[i].communityList.length; j < inLen; j++) {
            resultDatas.push({
              title: val[i].communityList[j].communityName,
              tags: ['未知'],
              position: val[i].communityList[j].address,
              ld: val[i].communityList[j].buildCount,
              fw: val[i].communityList[j].houseCount,
              projectCode: val[i].projectCode,
              projectName: val[i].projectName,
              communityId: val[i].communityList[j].communityId,
              city: val[i].communityList[j].city,
              cityCode: val[i].communityList[j].cityCode,
              yCoord: val[i].communityList[j].yCoord,
              xCoord: val[i].communityList[j].xCoord,
              isTitle: false,
              url: val[i].communityList[j].url
            });
          };
        };
        break;
      case 2:
        resultDatas.push({
          badge: '1',
          projectName: val.projectName,
          projectCode: val.projectCode,
          totalBuildingArea: val.totalBuildingArea,
          totalLandArea: val.totalLandArea,
          buildCount: val.buildCount,
          houseCount: val.houseCount,
          receivedDate: val.receivedDate,
          transferUnit: val.transferUnit,
          isTitle: true
        });
        for (let i = 0, outLen = val.communityPage.list.length; i < outLen; i++) {
          resultDatas.push({
            title: val.communityPage.list[i].communityName,
            tags: ['未知'],
            position: val.communityPage.list[i].address,
            ld: val.communityPage.list[i].buildCount,
            fw: val.communityPage.list[i].houseCount,
            projectCode: val.communityPage.list[i].projectCode,
            projectName: val.communityPage.list[i].projectName,
            communityId: val.communityPage.list[i].communityId,
            city: val.communityPage.list[i].city,
            cityCode: val.communityPage.list[i].cityCode,
            yCoord: val.communityPage.list[i].yCoord,
            xCoord: val.communityPage.list[i].xCoord,
            isTitle: false,
            url: val.communityPage.list[i].url
          });
        };

        break;
      default:
        resultDatas.push({
          title: val.communityName,
          tags: ['未知'],
          position: val.address,
          ld: val.buildCount,
          fw: val.houseCount,
          communityId: val.communityId,
          communityName: val.communityName,
          city: val.city,
          cityCode: val.cityCode,
          yCoord: val.yCoord,
          xCoord: val.xCoord,
          isTitle: false,
          url: val.url
        });
        break;
    };

    this.setState({
      resultDatas,
      showList: true,
      showMapDiv: false,
      showFilter: false
    });
  }
  showTotal(total) {
    return <span>共<span style={{ color: '#e22534' }}>{total}</span>条结果</span>;
  }

  filter() {
    this.setState({
      showList: false,
      showFilter: !this.state.showFilter,
      showMapDiv: false
    });
  }
  changeFilter(type, checkedValues) {

    let res = {
      type
    };
    this.setState({
      right: -380,
    });
    let postData = this.state.postData;
    postData.use = this.state.qsValue;//权属性质
    postData.isRent = this.state.zlValue;//租赁状态
    postData.assetStatus = this.state.zcValue;//资产状态
    switch (type) {
      case 'zlzt':
        this.setState({
          zlValue: checkedValues
        });
        res.checkedValues = checkedValues;
        postData.isRent = checkedValues;
        break;
      case 'qsxz':
        this.setState({
          qsValue: checkedValues
        });
        res.checkedValues = checkedValues;
        postData.use = checkedValues;
        break;
      case 'zczt':
        this.setState({
          zcValue: checkedValues
        });
        res.checkedValues = checkedValues;
        postData.assetStatus = checkedValues;
        break;
    };

    this.getMapData(this.formateData(postData));

  }

  closeInfo() {
    this.setState({
      right: -380
    });
  }
  // changeTools(nowType) {
  //   this.setState({
  //     nowType
  //   });
  // }
  onReceiveMessage(data) {
    let right = 0;
    let postData = {
      use: this.state.qsValue,//权属性质
      isRent: this.state.zlValue,//租赁状态
      assetStatus: this.state.zcValue,//资产状态
      province: data.data.province,
      city: data.data.city,
      area: data.data.district,
    };

    if (data.data.type === 'clickedXQ') {
      right = -380;
      this.setState({
        right
      });
      axios.get(Api.searchCommunityId, {
        params: {
          communityId: data.data.communityId
        }
      }).then(res => {
        if (res.data.entiy === null) {
          message.warn('暂无数据！');
        } else {
          this.setState({
            clickXQ: res.data.entiy,
            showMapDiv: true,
            showList: true,
            searchVal: '',
            res: [],
            resultDatas: [],
            page: 1
          });
        };
      });
    } else {
      this.receivedMapData(this.formateData(postData));
    };
    this.getMapData(this.formateData(postData));
    this.setState({
      right,
      cityData: data
    });
  }
  searchTransferUnit(searchVal, arr, page, sType) {
    // 搜索
    const that = this;

    this.setState({
      searchVal,
      arrVal: arr,
      right: -380
    });
    let url = '';
    let params = {
      ...this.formateData({
        use: this.state.qsValue,//权属性质
        isRent: this.state.zlValue,//租赁状态
        assetStatus: this.state.zcValue,//资产状态
      })
    };

    params.currentPage = page;
    let type = sType || Number(this.state.searchType);

    switch (type) {
      case 1:
        url = Api.searchTransferUnit;
        params.name = arr.props.children;
        break;
      case 2:
        url = Api.searchProjectName;
        params.name = arr.props.children;
        break;
      case 3:
        url = Api.searchCommunityName;
        params.address = arr.props.children;
        break;
    };

    axios.get(url, {
      params: {
        ...params
      }
    }).then((res) => {

      switch (type) {
        case 1:
          if (res.data.list.length === 0) {
            message.warn('暂无数据');
            this.setState({
              showList: false
            });
          } else {
            this.setState({
              communityVal: res.data.list,
              resultDatasCount: res.data.totalSize,
              showList: true,
              sendMapData: {
                type: 'search',
                searchType: Number(this.state.searchType),
                data: res.data.list,
              }
            });
            this.searchVal(res.data.list);
          };
          break;
        case 2:
          if (res.data.entiy === null) {
            message.warn('暂无数据');
            this.setState({
              showList: false
            });
          } else {
            this.setState({
              showList: true,
              communityVal: res.data.entiy.communityPage.list,
              resultDatasCount: res.data.entiy.communityPage.totalSize,
              sendMapData: {
                type: 'search',
                searchType: Number(this.state.searchType),
                data: res.data.entiy.communityPage.list,
              }
            });
            this.searchVal(res.data.entiy);
          };
          break;
        case 3:
          if (res.data.entiy === null) {
            message.warn('暂无数据');
            this.setState({
              showList: false
            });
          } else {
            this.setState({
              showList: true,
              communityVal: res.data.entiy,
              resultDatasCount: res.data.totalSize,
              sendMapData: {
                type: 'search',
                searchType: Number(this.state.searchType),
                data: res.data.entiy,
              }
            });
            this.searchVal(res.data.entiy);
          };

          break;
      };


    });
  }

  handleChange(searchVal, arr) {
    this.searchTransferUnit(searchVal, arr, this.state.page);
  };

  changeLeft(searchType) {
    this.setState({
      searchType,
      searchVal: '',
      res: [],
      resultDatas: [],
      showList: false,
      showMapDiv: false,
      page: 1
    });
  }
  handleSearch(searchContent) {
    this.setState({
      right: -380,
    });
    if (this.state.timer !== '') {
      clearTimeout(this.state.timer);
    };
    if (searchContent.length > 0) {
      this.setState({
        showLoading: true
      });
    };
    let timer = setTimeout(() => {
      const that = this;
      axios.get(Api.queryAsset, {
        params: {
          searchType: that.state.searchType,
          searchContent
        }
      }).then((res) => {
        this.setState({
          res: res.data
        });
        if (res.data.length === 0) {
          this.setState({
            showLoading: false
          });
        };
      });
    }, 600);
    this.setState({
      timer
    });
  }
  formateData(postData) {
    let data = JSON.parse(JSON.stringify(postData));
    let tmp = data.assetStatus;
    for (let i = 0, len = tmp.length; i < len; i++) {
      switch (tmp[i]) {
        case '接管中':
          tmp[i] = 5;
          break;
        case '待接管':
          tmp[i] = 7;
          break;
        case '已接管':
          tmp[i] = 8;
          break;
        case '运营中':
          tmp[i] = 9;
          break;
      }
    };
    data.use = data.use.join();
    data.isRent = data.isRent.join();
    data.assetStatus = data.assetStatus.join();
    return data;
  }
  componentWillMount() {
    let postData = {
      use: this.state.qsValue,//权属性质
      isRent: this.state.zlValue,//租赁状态
      assetStatus: this.state.zcValue,//资产状态
      province: '',
      city: '',
      area: '',
    };
    this.getMapData(this.formateData(postData));
    this.receivedMapData(this.formateData(postData));
  }
  receivedMapData(postData) {
    axios.get(Api.queryHouseCount, {
      params: {
        ...postData
      }
    }).then((res) => {
      this.setState({
        right: 0,
        infoData: res.data,
      });
    });
  }

  getMapData(postData) {
    function screenSelect() {
      return axios.get(Api.screenSelect, {
        params: {
          ...postData
        }
      });
    }

    function queryAreaByParams() {
      return axios.get(Api.queryAreaByParams, {
        params: {
          ...postData
        }
      });
    }

    axios.all([screenSelect(), queryAreaByParams()])
      .then(axios.spread((screenSelect, queryAreaByParams) => {
        // 两个请求现在都执行完成
        this.setState({
          sendMapData: {
            type: 'filter',
            data: {
              screenSelect: screenSelect.data,
              queryAreaByParams: queryAreaByParams.data
            }
          }
        });
      }));
  }

  changePage(current, size) {
    searchTransferUnit(this.state.searchVal, this.state.arrVal, current)
  }
  render() {
    const { infoData } = this.state;
    return (
      <div className={styles.mapBox}>
        <div className={styles.searchBox}>
          <InputGroup compact>
            <Select
              className={styles.select}
              defaultValue="1"
              onChange={this.changeLeft.bind(this)}
            >
              <Option value="1">划转单位</Option>
              <Option value="2">项目名称</Option>
              <Option value="3">地址</Option>
            </Select>
            <Select
              showSearch
              placeholder='请输入内容'
              className={styles.search}
              defaultActiveFirstOption={false}
              showArrow={true}
              filterOption={false}
              onSearch={this.handleSearch.bind(this)}
              onChange={this.handleChange.bind(this)}
              notFoundContent={this.state.showLoading ? <span>加载中<Icon type='loading' /></span> : <span>暂无数据</span>}
              onBlur={() => { this.setState({ showLoading: false }) }}
              value={this.state.searchVal}
            >

              {this.state.res.map((item, index) => (<Option key={index} value={item + index} title={item}>{item}</Option>))}
            </Select>
            <Tooltip placement="bottom" title='搜索'>
              <Button type="primary" icon="search" onClick={this.handleChange.bind(this, this.state.searchVal, this.state.arrVal)} />
            </Tooltip>
            &emsp;
            <Tooltip placement="bottom" title='地图筛选条件'>
              <Button type="primary" icon="filter" onClick={this.filter.bind(this)}>
                筛选条件
              </Button>
            </Tooltip>
          </InputGroup>
          <div className={styles.searchResult} style={{
            opacity: this.state.showList ? '1' : '0'
          }}>
            <QueueAnim component='ul' className={styles.mandatory}>
              {this.state.showList && this.state.resultDatas.length !== 0 ?
                this.state.resultDatas.map((item, index) => {
                  if (item.isTitle) {
                    return (
                      <li key={index} className={styles.searchResultItem}
                        style={{
                          position: 'sticky',
                          top: 0,
                          zIndex: 99
                        }}
                      >
                        <div className={`clearfix ${styles.itemTitle}`}>
                          <Badge count={item.badge} style={{ backgroundColor: '#52c41a' }} />
                          &emsp;
                          {item.projectName}
                        </div>
                        <Row>
                          <Col className='mrb5' span={11} title={item.projectCode}>
                            <span className='label'>项目编号：</span>
                            {item.projectCode}
                          </Col>
                          <Col className='mrb5' span={11} offset={1}>
                            <span className='label' title={item.totalBuildingArea}>总建面：</span>
                            {item.totalBuildingArea}
                          </Col>
                          <Col className='mrb5' span={11} title={item.totalLandArea}>
                            <span className='label'>土地面积：</span>
                            {item.totalLandArea}
                          </Col>
                          <Col className='mrb5' span={11} offset={1} title={item.buildCount}>
                            <span className='label'>楼栋数量：</span>
                            {item.buildCount}
                          </Col>
                          <Col className='mrb5' span={11} title={item.houseCount}>
                            <span className='label'>房产数量：</span>
                            {item.houseCount}
                          </Col>
                          <Col className='mrb5' span={11} offset={1} title={item.transferUnit}>
                            <span className='label'>划转单位：</span>
                            {item.transferUnit}
                          </Col>
                          <Col className='mrb5' span={11} title={item.receivedDate}>
                            <span className='label'>接管时间：</span>
                            {item.receivedDate}
                          </Col>
                        </Row>
                      </li>
                    );
                  } else {
                    return (
                      <li key={index} className={styles.searchResultItem}>
                        <div className={`clearfix ${styles.itemTitle}`}>
                          <span className={styles.redC}>
                            <Link target="_blank" to={{
                              pathname: '/fe/assetMap/communityDetails',
                              state: {
                                communityId: item.communityId
                              },
                              search: `?communityId=${item.communityId}`,
                            }}>
                              {item.title}
                            </Link>
                          </span>
                        </div>
                        <div className={`clearfix ${styles.itemContent}`}>
                          <div className={`pull-left ${styles.w240}`}>
                            <p title={this.state.clickXQ.position}>{item.position}</p>
                            <p>资产数量：</p>
                            <div className="clearfix">
                              <p className={`pull-left ${styles.w50}`}>楼栋：{item.ld}</p>
                              <p className={`pull-left ${styles.w50}`}>房屋：{item.fw}</p>
                            </div>
                          </div>
                          <div className={`pull-left ${styles.w100}`}>
                            <img src={item.url === '-' || !item.url ? noPic : `http://192.168.50.55:55555/res_file${item.url}`} />
                          </div>
                        </div>
                        <div></div>
                      </li>
                    )
                  }

                })
                : null
              }
              {
                this.state.showMapDiv ?
                  <li key='showMapDiv' className={styles.searchResultItem}>
                    <div className={`clearfix ${styles.itemTitle}`}>
                      <span className={styles.redC}>
                        <Link target="_blank" to={{
                          pathname: '/fe/assetMap/communityDetails',
                          state: {
                            communityId: this.state.clickXQ.communityId
                          },
                          search: `?communityId=${this.state.clickXQ.communityId}`,
                        }}>
                          {this.state.clickXQ.communityName}
                        </Link>
                      </span>
                    </div>
                    <div className={`clearfix ${styles.itemContent}`}>
                      <div className={`pull-left ${styles.w240}`}>
                        <p title={this.state.clickXQ.address}>{this.state.clickXQ.address}</p>
                        <p>资产数量：</p>
                        <div className="clearfix">
                          <p className={`pull-left ${styles.w50}`}>楼栋：{this.state.clickXQ.buildCount}</p>
                          <p className={`pull-left ${styles.w50}`}>房屋：{this.state.clickXQ.houseCount}</p>
                        </div>
                      </div>
                      <div className={`pull-left ${styles.w100}`}>
                        <img src={this.state.clickXQ.url === '-' || !this.state.clickXQ.url ? noPic : `http://192.168.50.55:55555/res_file${this.state.clickXQ.url}`} />
                      </div>
                    </div>
                    <div></div>
                  </li> : null
              }
            </QueueAnim>
            {
              this.state.showMapDiv ? null : <Pagination size="small" total={this.state.resultDatasCount} showTotal={this.showTotal.bind(this)} className='pd10' style={{
                padding: 10
              }}
                onChange={this.changePage.bind(this)}
              />
            }
          </div>
          <QueueAnim>
            {this.state.showFilter ?
              [
                <div className={styles.filter} key='filter'>
                  <div className={styles.filterItem}>
                    <div className={styles.filterHeader}>
                      房产用途
                    </div>
                    <div>
                      <CheckboxGroup options={this.state.qsxz}
                        onChange={this.changeFilter.bind(this, 'qsxz')}
                        value={this.state.qsValue}
                      />
                    </div>
                  </div>
                  <div className={styles.filterItem}>
                    <div className={styles.filterHeader}>
                      资产状态
                    </div>
                    <div>
                      <CheckboxGroup options={this.state.zczt}
                        onChange={this.changeFilter.bind(this, 'zczt')}
                        value={this.state.zcValue}
                      />
                    </div>
                  </div>
                  <div className={styles.filterItem}>
                    <div className={styles.filterHeader}>
                      租赁状态
                    </div>
                    <div>
                      <CheckboxGroup options={this.state.zlzt}
                        onChange={this.changeFilter.bind(this, 'zlzt')}
                        value={this.state.zlValue}
                      />
                    </div>
                  </div>
                </div>
              ]
              :
              null
            }
          </QueueAnim>
        </div>
        {Number(sessionStorage.getItem('isMap')) === 1 ?
          <div>
            <IframeComm
              attributes={{
                src: "/gis/map.html",
                style: {
                  width: '100%',
                  height: '100%',
                  top: '0px',
                  left: '0px',
                  position: "absolute"
                }
              }}
              postMessageData={this.state.sendMapData}
              handleReceiveMessage={this.onReceiveMessage.bind(this)}
            />
          </div>
          :
          null
        }
        <div className={styles.dataInformation} style={{
          right: this.state.right
        }}>
          <div className={styles.toolBox}>
            <div onClick={this.closeInfo.bind(this)}>
              <Tooltip placement="left" title='关闭'>
                <Icon type="arrow-right" />
              </Tooltip>
            </div>
          </div>
          <div className={styles.infoMain}>
            <Info data={infoData} cityData={this.state.cityData} />
            <Chart data={infoData} />
          </div>
        </div>
      </div>
    );
  }
}

export default AssetMap;
